import React, { PropTypes, Component } from 'react';
import { connect } from 'react-redux';
import {Link } from 'dva/router';
import { notification,Button, Modal, Form, Input,Upload, message,Icon,Spin,Row, Col } from 'antd';
import styles from './uploadfiles.less';
import $ from 'jquery';
import api from '../../../api';


let type;
const mapDispatchToProps = {
 uploadFiles: query => ({
	 type: 'pdtmanagement/uploadFiles',
	 payload: query || {},
 }),
};

@connect( null,mapDispatchToProps)
export default class Uploadfiles extends Component {
	constructor(props) {
		super(props);
		this.state = {
			fileList: [],
			visible: false,
			loading: false,
			name:props.name
		};
	}
	showModal = () => {
		this.setState({
		 visible: true,
		});
	}
	downLoad=()=>{
		const {name} = this.props;
		if(name == '按数量'){
	 		type = 'amount';
	 		window.location.href=location.href.indexOf('localhost')>-1?`/api/marketdata/downLoadHoldTemplate?type=${type}`:`/thfx/api/marketdata/downLoadHoldTemplate?type=${type}`;
	 	}else{
	 		if(name == '按权重'){
	 			type = 'weight';
	 			window.location.href=location.href.indexOf('localhost')>-1?`/api/marketdata/downLoadHoldTemplate?type=${type}`:`/thfx/api/marketdata/downLoadHoldTemplate?type=${type}`;
	 		}
	 	}
	}
	handleOk = (e) => {
	 	const { fileList,loading,visible } = this.state;
	 	const {productId,effectiveDate,changeName,name,uploadFiles} = this.props;
	 	if(name == '按数量'){
	 		type = 'amount'
	 	}else if(name == '按权重'){
	 		type = 'weight'
	 	}else if(name == '按产品估值'){
	 		type = 'PV'
	 	}
		const formData = new FormData();
		fileList.forEach((file) => {
			formData.append('file', file);
			formData.append('productId', productId);
		});
		this.setState({
			loading: true,
			visible: true,
			name:'导入中...'
		});
		if(type == 'amount' || type == 'weight'){
			$.ajax({
			url:location.href.indexOf('localhost')>-1?`/api/portfolio/uploadProduct/${productId}?type=${type}`:`/thfx/api/portfolio/uploadProduct/${productId}?type=${type}`,
			method: 'post',
			enctype: "multipart/form-data",
			processData: false,
			headers: {
				ContentType: 'application/json',
				XRequestedWith: 'XMLHttpRequest',
				ContentType: 'text/plain',
			},
			data: formData,
		  contentType: false,
		  processData: false,
		  success: (data) => {
		  	if(data.code == 1){
						this.setState({
							visible: false,
							loading: false,
							fileList: [],
							name:name
						});
						notification['error']({
						 message:data.msg,
						});
					}else{
						this.setState({
							visible: false,
							loading: false,
							fileList: [],
							name:name
						});
						notification['success']({
				    message: '上传成功',
				  });
		  	}
		  },
		  error: (data) => {
		  	this.setState({
						loading: false,
						name:name
					});
					if(+data.status === 403){
						notification['error']({
				    message: '登录超时!',
				  });
						window.location.href = `${location.href.split('#')[0]}#/login`;
					}
					if(+data.status === 400){
						notification['warning']({
				    message: '请选择持仓文件!',
				  });
					}
					if(+data.status !== 200){
						notification['warning']({
				    message: '导入失败!',
				  });
					}
					message.config({
		  		duration: 3,
					});
		  	}
			});
		}else if(type == 'PV'){
			$.ajax({
			url:location.href.indexOf('localhost')>-1?`/api/portfolio/uploadValuationTable/${productId}`:`/thfx/api/portfolio/uploadValuationTable/${productId}`,
			method: 'post',
			enctype: "multipart/form-data",
			processData: false,
			headers: {
				ContentType: 'application/json',
				XRequestedWith: 'XMLHttpRequest',
				ContentType: 'text/plain',
			},
			data: formData,
		  contentType: false,
		  processData: false,
		  success: (data) => {
		  	if(data.code == 1){
						this.setState({
							visible: false,
							loading: false,
							fileList: [],
							name:name
						});
						notification['error']({
						 message:data.msg,
						});
					}else{
						this.setState({
							visible: false,
							loading: false,
							fileList: [],
							name:name
						});
						notification['success']({
				    message: '上传成功',
				  });
		  	}
		  },
		  error: (data) => {
		  	console.log(11123313,data)
		  	this.setState({
						loading: false,
						name:name
					});
					if(+data.status === 403){
						notification['error']({
				    message: '登录超时!',
				  });
						window.location.href = `${location.href.split('#')[0]}#/login`;
					}
					if(+data.status === 400){
						notification['warning']({
				    message: '请选择持仓文件!',
				  });
					}
					if(+data.status !== 200){
						notification['warning']({
				    message: '导入失败!',
				  });
					}
					message.config({
		  		duration: 3,
					});
		  	}
			});
		}
		
	}

	handleCancel = (e) => {
		this.setState({
			visible: false,
			loading:false,
			fileList: [],
		});
	}
	render() {
		const { visible,fileList } = this.state;
		const { sidebarFold } = this.props;
		const props = {
			multiple: false,
			action:location.href.indexOf('localhost')>-1?'/api/portfolio/uploadProduct':'/thfx/api/portfolio/uploadProduct',
			onRemove: (file) => {
				this.setState(({ fileList }) => {
					const index = fileList.indexOf(file);
					const newFileList = fileList.slice();
					newFileList.splice(index, 1);
					return {
						fileList: newFileList,
					};
				});
			},
			beforeUpload: (file) => {
				this.setState(({ fileList }) => ({
					fileList: [...fileList, file],
				}));
				console.log('fileList>>>',file)

				return false;
			},
			fileList: this.state.fileList,
		};
		const uploadButton = (
		<Button>
				<Icon type="upload" />选择持仓文件
			</Button>
		);

		return (
			<Link>
				{/*<Spin tip="上传中..." spinning={this.state.loading} className={styles.loads}/>*/}
				<span type="primary" onClick={this.showModal} className={styles.uploadbtn}>{this.state.name}</span>
				<Modal
					title="上传文件"
					visible={this.state.visible}
					onChange={this.props.changeName}
					onOk={this.handleOk}
					onCancel={this.handleCancel}
				>
					<div>
						<Row>
							<Col className={styles.msgnote}>请确保持仓表的调整日期大于产品的生效时间:{`${this.props.effectiveDate}`}</Col>
						</Row>
						<Row type="flex" justify="space-around" align="middle">
							<Col span={12}>
								<Button type="primary" className={styles.exportButton} onClick={this.downLoad}>下载持仓单范例</Button>
							</Col>
							<Col span={12}>
								<Upload {...props}>
									{fileList.length >= 1 ? null : uploadButton}
								</Upload>
							</Col>
						</Row>
					</div>
					<Spin tip="上传中..." spinning={this.state.loading} className={styles.loads}/>
				</Modal>
			</Link>
		);
	}
}
